// 测试axios
import axios from 'axios'
function axiosTest(method,url,data) {
  return new Promise((resolve, reject) => {
    axios({
      method: method,
      url,
      data: data,
    })
    .then(r => {
      // console.log(r)
      resolve(r)
    })
    .catch(e =>{
    //console.log(e)
      reject(e)
    })
  })
}
// req.url 参数
function getUrlParam(url, parm) {
  let theRequest = new Object()
  if (url.indexOf("?") != -1) {
    let str = url.split('?')[1]
    let strs = str.split("&")
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1])
    }
  }
  return theRequest[parm]
}
// 是否为空
function isNull(obj) {
  if (obj == null) return true
  else if (obj == undefined) return true
  else if (typeof(obj)=='string' && obj == 'null') return true
  else if (typeof(obj)=='string' && obj == 'undefined') return true
  else if (typeof(obj)=='string' && obj == '') return true
  else if (typeof(obj)=='string' && obj == '[]') return true
  else if (typeof(obj)=='string' && obj == '{}') return true
  else if (obj == []) return true
  else if (obj == {}) return true
  else if (obj.length <= 0) return true
  else return false
}
// 是否包含某字符
function hasStr(S, str) {
  return S.indexOf(str) >= 0
}
// 获取文件名与扩展名
function getNameAndExt(filename) {
  let result = {}
  result.name = filename.split('').reverse().join('').split('.')[1].split('').reverse().join('')
  result.ext = filename.split('').reverse().join('').split('.')[0].split('').reverse().join('')
  return result
}
// 数组去重
function distinctArr(array) {
  let temp = []
  for (let i in array) { 
    if (array[i] && temp.indexOf(array[i]) == -1 && array[i].length > 0) {
      temp.push(array[i])
    }
  }
  return temp
}
// 10以内随机字符串
function randomString10(len) {
  len = len || 26
  let $chars = 'abcdefghijklmnopqrstuvwxyz'
  let maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}
// 点击图片在新窗口显示大图
function showRealImg(imgurl, title) {
  const img = new Image()
  img.src = imgurl
  const newWin = window.open('', '_blank')
  newWin.document.write(img.outerHTML)
  newWin.document.title = title
  newWin.document.close()
}
// username格式检查
function nameChecked(name) {
  let result = 'success'
  name = name.toLowerCase()
  if (name[0]*0 === 0) {
    result = '用户名首位只能是字母'
  }
  let nameBase = '1234567890abcdefghijklmnopqrstuvwxyz'
  for(let i in name) {
    if (nameBase.indexOf(name[i]) < 0) {
      result = '用户名只能包含数字或字母'
    }
  }
  return result
}
// username解码
function nameDecode(code) {
  let res = {}
  res.msg = 'success'
  code = code.substring(80, code.length)
  code = code.toUpperCase()
  let nameBase = '1234567890abcdefghijklmnopqrstuvwxyz'
  let codeBase = '0ZYX8WVU6TSR4QPO2NM9LK7JI5HG3FE1DCBA'
  let signArr = []
  for(let i in code) {
    if (codeBase.indexOf(code[i]) < 0) {
      res.msg = '用户名解码失败，请重试'
    } else {
      signArr.push(codeBase.indexOf(code[i]))
    }
  }
  let name = ''
  for(let i in signArr) {
    name = name + nameBase[signArr[i]]
  }
  res.data = name
  return res
}
// input 禁止输入空格
function inputNoSpace(s) {
  let r = s.replace(/[ ]/g,'')
  return r
}
/***********************************************
************************************************ 
*  日期时间处理
************************************************
************************************************/
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 日期时间格式化
function formatDateTime(date, connector) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const millisecond = date.getMilliseconds()

  if (connector === '') {
    return [year, month, day].map(formatNumber).join('')
    + [hour, minute, second].map(formatNumber).join('')
    + [millisecond].map(formatNumber)
  } else {
    return [year, month, day].map(formatNumber).join('-')
    + ' ' + [hour, minute, second].map(formatNumber).join(':')
    + '.' + [millisecond].map(formatNumber)
  }
  
}
// 时间格式化
function formatTime(date, connector) {
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [hour, minute, second].map(formatNumber).join(connector)
}
// 日期格式化
function formatDate(date, connector) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join(connector)
}
// 日期格式化（加减月）
function formatDateDiffMonth(date, diffMonth) {
  let diffMonthValue = diffMonth%12
  let year = date.getFullYear()
  let month = date.getMonth() + 1 + diffMonthValue
  let day = date.getDate()
	year = year + (diffMonth > 0 ? Math.floor(diffMonth/12) : Math.ceil(diffMonth/12))
	if (month > 12) {
		let monthValue = month%12
		year = year + (month > 0 ? Math.floor(month/12) : Math.ceil(month/12))
		month = monthValue
	} else if (month <= 0) {
		let monthValue = month + 12
		year = year - 1
		month = monthValue
	}
  let newdate = [year, month, day].map(formatNumber).join('-')
  const newyear = newdate.substring(0, 5)
  const newday = newdate.substring(5, newdate.length)
  if (newday == '02-28') newdate = newyear + '03-01'
  if (newday == '02-29') newdate = newyear + '03-01'
  if (newday == '02-30') newdate = newyear + '03-01'
  if (newday == '02-31') newdate = newyear + '03-01'
  if (newday == '04-31') newdate = newyear + '05-01'
  if (newday == '06-31') newdate = newyear + '07-01'
  if (newday == '09-31') newdate = newyear + '10-01'
  if (newday == '11-31') newdate = newyear + '12-01'
  return newdate
}
// 格林威治时间转换为东八
function formatGmt8(datetime) {
  if (this.isNull(datetime)) return ''
  const date = datetime.indexOf('T') >= 0 ? datetime.split('T')[0] : datetime.split(' ')[0]
  const time = datetime.indexOf('T') >= 0 ? datetime.split('T')[1] : datetime.split(' ')[1]
  let time1 = time.split(':')[0] * 1 + 8
  time1 = time1 >= 24 ? time1 - 24 : time1
  time1 = time1 < 10 ? '0' + time1 : time1
  const time2 = time.split(':')[1]
  const time3 = time.split(':')[2].split('.')[0]
  return date + ' ' + time1 + ':' + time2 + ':' + time3
}
// 东八时间格式化
function formatGmt(datetime) {
  if (this.isNull(datetime)) return ''
  const date = datetime.indexOf('T') >= 0 ? datetime.split('T')[0] : datetime.split(' ')[0]
  const time = datetime.indexOf('T') >= 0 ? datetime.split('T')[1] : datetime.split(' ')[1]
  if (!time) return date
  let time1 = time.indexOf(':')>=0?time.split(':')[0] * 1 : time
  time1 = time1 >= 24 ? time1 - 24 : time1
  time1 = time1 < 10 ? '0' + time1 : time1
  const time2 = time.split(':')[1]
  const time3 = time.split(':')[2].split('.')[0].split('+')[0]
  return date + ' ' + time1 + ':' + time2 + ':' + time3
}
// 秒显示为汉字信息
function formatSeconds(s) {
  // console.log(s)
  let result = '未知时间'
  let fz = s / 60 | 0
  if (fz <= 60) {
    result = fz + '分钟'
  } else {
    let xs = s / 3600
    if (xs <= 24) {
      let xsz = xs | 0
      let xsx = (xs - xsz) * 60 | 0
      result = xsz + '小时' + xsx + '分'
    } else {
      let tian = s / 86400
      let tianz = tian | 0
      let xs = (tian - tianz) * 24
      let xsz = xs | 0
      let xsx = (xs - xsz) * 60 | 0
      result = tianz + '天' + xsz + '小时' + xsx + '分'
    }
  }
  return result
}
// 日期显示为汉字转换
function dateFormatStr(date = '') {
	if (date.indexOf('-')>=0) {
		let d = date
		date = `${d.split('-')[0]}年${d.split('-')[1]}月${d.split('-')[2]}日`
	} else {
		date = date.replace('年','-')
		date = date.replace('月','-')
		date = date.replace('日','')
	}
	return date
}
// 按时间生成唯一SN
function dateFormatSN(date = new Date()) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  const millisecond = date.getMilliseconds()

  // return randomString10(5).toUpperCase()+[year, month, day].map(formatNumber).join('')
  //   + [hour, minute, second].map(formatNumber).join('')
  //   + [millisecond].map(formatNumber)

  return 'board_sn_test'+[year, month, day].map(formatNumber).join('')
    + [hour, minute, second].map(formatNumber).join('')
    + [millisecond].map(formatNumber)
}

/***********************************************
  ************************************************ 
  *  排序
  ************************************************
  ************************************************/
// 正序
function sortAsc(arr, title) {
  if (this.isNull(arr)) return
  arr = arr.sort(function (a, b) {
    if (typeof (a[title]) == 'string')
      return a[title].localeCompare(b[title])
    else
      return a[title] - b[title]
  })
  return arr
}
// 逆序
function sortDesc(arr, title) {
  if (this.isNull(arr)) return
  arr = this.sortAsc(arr, title).reverse()
  return arr
}

/***********************************************
  ************************************************ 
  *  中英文判断转换
  ************************************************
  ************************************************/
// 判断是否中文英文数字
function inputJudge(v) {
  const chinese = /.*[\u4e00-\u9fa5]+.*$/
  const number = /^\d+$/
  const englishAndNum = /^[A-Za-z0-9]*$/
  if (chinese.test(v)) return '包含汉字'
  if (number.test(v)) return '只包含数字'
  if (englishAndNum.test(v)) return '包含字母或数字'
}
// 英文逗号转为中文逗号
function replaceEnglishDot(v) {
  //寻找每一个英文逗号，并替换
  while (v.indexOf(",") != -1) {
    v = v.replace(",", "，")
  }
  return v
}
// 复制文本
async function copyJSON(text) {
  let target = document.createElement('input') //创建input节点
  target.value = text // 给input的value赋值
  document.body.appendChild(target) // 向页面插入input节点
  target.select() // 选中input
  try {
    await document.execCommand('Copy') // 执行浏览器复制命令
    // console.log('复制成功')
    target.remove()
    return true
  } catch {
    // console.log('复制失败')
    target.remove()
    return false
  }
}
// 图片转base64
function fileToBase64(file) {
  // 直接将处理结果返回
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    let fileResult = "";
    reader.readAsDataURL(file);
    reader.onload = () => {
      fileResult = reader.result.toString();
    };
    reader.onerror = (error) => {
      reject(error);
    };
    reader.onloadend = () => {
      resolve(fileResult);
    };
  });
}
// base64转图片
function base64ToFile(base64, fileName) {
  let arr = base64.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bytes = atob(arr[1]);
  let n = bytes.length;
  let ia = new Uint8Array(n);
  while (n--) {
    ia[n] = bytes.charCodeAt(n);
  }
  return new File([ia], fileName, { type: mime });
}

// 管理el—tabs状态
function elTabStatus(f,t) {
  if (f == 'init') {
    sessionStorage.removeItem('el_tab_open')
    sessionStorage.removeItem('el_tab_current')
  } else if (f == 'set') {
    if (typeof(t) == 'object') {
      let s = ''
      for(let i in t) {
        s=s+t[i].name+','
      }
      sessionStorage.setItem('el_tab_open',s)
    }
    if (typeof(t) == 'string') {
      sessionStorage.setItem('el_tab_current',t)
    }
  } else if (f == 'get') {
    let s = sessionStorage.getItem('el_tab_open')
    let c = sessionStorage.getItem('el_tab_current')
    return { tabs: s, tab: c}
  }
}
// 用户状态转为文字
function userStatus2String(status) {
  let res = '未知'
  switch (status) {
    case 0:
      res = '未绑定邮箱'
      break;
    case 1:
      res = '未确认邮箱'
      break;
    case 2:
      res = '已确认邮箱'
      break;
    case 999:
      res = '管理员'
      break;
    default:
      break;
  }
  return res
}
// 用户类型
function cilentType(s) {
  let r = '未知'
  if (s.length == 4) r = '系统默认'
  if (s.length == 8) r = '代理商/甲方'
  if (s.length == 12) r = '商户' 
  return r
}
// 判断是否超级管理员或默认操作员
function isAdmin(n) {
  let r = false
  if (n.indexOf('超级管理员') >= 0) r=true
  if (n.indexOf('默认操作员') >= 0) r=true
  return r
}

export default {
  axiosTest, getUrlParam, isNull, hasStr, getNameAndExt, distinctArr, randomString10, showRealImg, nameChecked, nameDecode, inputNoSpace,
  formatDateTime, formatTime, formatDate, formatDateDiffMonth, formatGmt8, formatGmt, formatSeconds, dateFormatStr,dateFormatSN,
  sortAsc, sortDesc, inputJudge, replaceEnglishDot, copyJSON, fileToBase64, base64ToFile, elTabStatus, 
  userStatus2String, cilentType, isAdmin
}